// TinyPPDlg.cpp : implementation file
//

#include "stdafx.h"
#include "TinyPP.h"
#include "TinyPPDlg.h"
#include "tinyxml/tinyxml.h"
#include <Urlmon.h>

#include "util.h"
#include "OPMLProcessor.h"
#include "BlogLinesSyn.h"
#include "AddFeedWizardDlg.h"
#include "RSSFeed.h"
#include "DBManager.h"
#include "GroupSettingsDlg.h"
#include "AboutDlg.h"
#include "FeedFetcher.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif



/////////////////////////////////////////////////////////////////////////////
// CTinyPPDlg dialog

CTinyPPDlg::CTinyPPDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTinyPPDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CTinyPPDlg)
	m_strRSSLink = _T("http://spaces.msn.com/members/jj20050607/feed.rss");
	m_strFetchProgress = _T("fetching states");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CTinyPPDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CTinyPPDlg)
	DDX_Control(pDX, IDC_TREE1, m_feedTree);
	DDX_Control(pDX, IDC_LIST2, m_ItemList);
	DDX_Text(pDX, IDC_EDIT1, m_strRSSLink);
	DDX_Control(pDX, IDC_EXPLORER1, m_Browser);
	DDX_Text(pDX, IDC_STATIC1, m_strFetchProgress);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CTinyPPDlg, CDialog)
	//{{AFX_MSG_MAP(CTinyPPDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_LBN_SELCHANGE(IDC_LIST2, OnSelchangeList2)
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE1, OnSelchangedTree1)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
	ON_MESSAGE(WM_FPH_MSG, OnFPH)
	ON_BN_CLICKED(IDC_BUTTON4, OnButton4)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CTinyPPDlg message handlers

BOOL CTinyPPDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
/*	HTREEITEM feedroot = m_feedTree.InsertItem(_T("Feeds"),0,0);
	m_feedTree.InsertItem(_T("http://spaces.msn.com/members/jj20050607/feed.rss"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://feeds.feedburner.com/APointAtTheWeb"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://englishblog.org/feed/"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://www.perlchina.org/index.rdf"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://www.newsmth.org/rss.php?gJoke"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://blog.vckbase.com/rss.html"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://www.shuanga.com/rss.xml"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://blog.csdn.net/jiangredsheep/rss.aspx"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://sfw.FlickrLicio.us/feed"),0,0,feedroot);
	m_feedTree.InsertItem(_T("http://www.qiushibaike.com/rss.xml"),0,0,feedroot);

	m_feedTree.Expand(feedroot,TVE_EXPAND);
*/	
	m_feedTree.InitTree();
	FeedFetcher::Instance()->SetFPH(this);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CTinyPPDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CTinyPPDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CTinyPPDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CTinyPPDlg::OnOK() 
{
	UpdateData();
	
	if ( URLDownloadToFile( NULL, m_strRSSLink, _T("temp.xml"),0, NULL ) != S_OK ){
            MessageBox("Update RSS source failed");
			return;
    }
	
	RSSParser parser;
	if(!parser.ParseFile("temp.xml",&m_Feed))
		return;
	vector<RSSItem> *items=m_Feed.GetItems();
	m_ItemList.ResetContent();
	for(vector<RSSItem>::iterator i=items->begin();i!=items->end();i++){
		string title=i->title;
		m_ItemList.AddString( UTF8_to_ANSI(i->title.c_str()).c_str());
	}

//	CDialog::OnOK();
}

void CTinyPPDlg::OnSelchangeList2() 
{
	int nIdx = m_ItemList.GetCurSel();
	if(nIdx == LB_ERR)
		return;
	
	//vector<RSSItem> *items=m_Feed.GetItems();
	vector<RSSItem> *items=&m_items;
	CStdioFile tempHTMLFile;
	if( !tempHTMLFile.Open("c:/temp.html",CFile::modeCreate|CFile::modeWrite) )
		return;
	tempHTMLFile.WriteString("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>\n<body>\n<h1>");
	tempHTMLFile.WriteString( (*items)[nIdx].title.c_str());
	tempHTMLFile.WriteString("</h1>\n");	
	tempHTMLFile.WriteString( (*items)[nIdx].description.c_str());
	tempHTMLFile.WriteString("</body>");
	tempHTMLFile.Close();
	m_Browser.Navigate("file://c:/temp.html",NULL,NULL,NULL,NULL);
}

void CTinyPPDlg::OnSelchangedTree1(NMHDR* pNMHDR, LRESULT* pResult) 
{	
	LPNMTREEVIEW pNMTreeView = reinterpret_cast <LPNMTREEVIEW>(pNMHDR);
    TVITEM* pItem = &pNMTreeView->itemNew ;	
	RSSFeed* pFeed = m_feedTree.GetRSSFeed(pItem->hItem);
	if(!pFeed)
		return;
	m_strRSSLink = pFeed->GetLink();

	UpdateData(FALSE);

	//OnOK();
	
	//FeedFetcher::Instance()->FetchAFeed(pFeed);
	
	m_ItemList.ResetContent();
	DBManager::Instance()->GetItems(pFeed,m_items);
	vector<RSSItem>* items=&m_items;
	for(vector<RSSItem>::iterator i=items->begin();i!=items->end();i++){
		string title=i->title;
		m_ItemList.AddString(UTF8_to_ANSI(i->title.c_str()).c_str());
	}

	*pResult = 0;
}

void CTinyPPDlg::OnButton1() 
{
	char strCurDir[MAX_PATH];
	GetCurrentDirectory(MAX_PATH,strCurDir);

	CFileDialog fd(TRUE, NULL, strcat(strCurDir,"\\default_opml.xml"), OFN_FILEMUSTEXIST);
 
	if (fd.DoModal() != IDOK)
		return;

	OPMLProcessor processor;
	processor.ParseFile(fd.GetPathName());
	processor.SynFeedTree(&m_feedTree);
}


void CTinyPPDlg::OnButton2() 
{
	CString strBloglinesHead = _T("http://www.bloglines.com/export?id=");
	CBlogLinesSynDlg dlg;
	if(dlg.DoModal() != IDOK){
		return;
	}
	
	if ( URLDownloadToFile( NULL, strBloglinesHead+dlg.m_strBlogLinesAccount, _T("bloglines.xml"),0, NULL ) != S_OK ){
            MessageBox("access bloglines failed");
			return;
    }

	OPMLProcessor processor;
	processor.ParseFile("bloglines.xml");
	processor.SynFeedTree(&m_feedTree);
}

void CTinyPPDlg::OnButton3() 
{
	FeedFetcher::Instance()->FetchAGroup(0);
}

void CTinyPPDlg::OnFinishFetchAFeed(int nID, int nNum)
{
	m_strFetchProgress.Format("Feed: %d with %d items finished",nID,nNum);
	this->SendMessage(WM_FPH_MSG);
}

LRESULT CTinyPPDlg::OnFPH(WPARAM wParam, LPARAM lParam)
{
	UpdateData(FALSE);
	return 0;
}

void CTinyPPDlg::OnButton4() 
{
	FeedFetcher::Instance()->StopFetching();
}
